package com.lfs.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.lfs.admin.dao.*;
import com.lfs.admin.feign.AdapterFeignService;
import com.lfs.admin.model.dto.PddProductPropertyDto;
import com.lfs.admin.model.dto.SpontaneousTitleDto;
import com.lfs.admin.model.dto.WordLibraryDto;
import com.lfs.admin.model.entity.AgtWalletDetailEntity;
import com.lfs.admin.model.entity.dataPackage.*;
import com.lfs.admin.model.entity.ShopEntity;
import com.lfs.admin.model.vo.*;
import com.lfs.admin.model.vo.dataPackage.DataUploadVo;
import com.lfs.admin.service.DataRepositoryService;
import com.lfs.admin.service.ShopService;
import com.lfs.admin.service.system.TokenService;
import com.lfs.admin.util.ExeclUtil;
import com.lfs.admin.util.RandomUtil;
import com.lfs.base.dto.Result;
import com.lfs.base.exception.BusinessException;
import com.lfs.base.exception.ServiceException;
import com.lfs.base.util.CollectionUtils;
import com.lfs.base.util.ObjectUtils;
import com.lfs.base.util.StringUtils;
import com.lfs.common.constant.CommonConstants;
import com.lfs.common.core.domain.entity.SysUser;
import com.lfs.common.core.domain.model.LoginUser;
import com.lfs.common.core.redis.RedisCache;
import com.lfs.common.utils.ServletUtils;
import com.lfs.dao.entity.PageBean;
import com.lfs.interfaces.dao.AgentWalletDao;
import com.lfs.interfaces.dto.TokenCreateDto;
import com.lfs.interfaces.model.vo.MallInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DataRepositoryServiceImpl implements DataRepositoryService {

    private final Logger logger = LoggerFactory.getLogger(DataRepositoryServiceImpl.class);

    @Autowired
    private DataRepositoryDao dataRepositoryDao;

    @Autowired
    private DataUploadDao dataUploadDao;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AdapterFeignService adapterFeignService;
    @Autowired
    private ShopService shopService;

    @Autowired
    private ProductTypeDao productTypeDao;

    @Autowired
    private ProductPropertyTemplateDao productPropertyTemplateDao;

    @Autowired
    private TitleTemplateDao titleTemplateDao;

    @Autowired
    private TitleWordDao titleWordDao;

    @Autowired
    private DataUploadDetailDao dataUploadDetailDao;

    @Autowired
    private DataUploadImageDao dataUploadImageDao;

    @Autowired
    private DataReleaseTaskDao dataReleaseTaskDao;

    @Autowired
    private DataReleaseDetailDao dataReleaseDetailDao;

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private AgtWalletInfoDao agtWalletInfoDao;

    @Autowired
    private AgentWalletDao agentWalletDao;

    @Resource
    private RedisCache redisCache;

    @Override
    public PageBean<DataRepositoryEntity> queryDataRepositoryList(DataRepositoryVo dataRepositoryVo) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        String agtNo = StringUtils.isBlank(user.getUserName()) ? "error" : user.getUserName();
        dataRepositoryVo.setAgtNo(agtNo);
        List<DataRepositoryEntity> dataRepositoryEntities = Lists.newArrayList();
        try {
            PageHelper.startPage(dataRepositoryVo.getCurrentPage(), dataRepositoryVo.getPageSize());
            dataRepositoryEntities = dataRepositoryDao.queryDataRepositoryList(dataRepositoryVo);

        } catch (Exception e) {
            logger.error("查询数据仓库列表异常={}",e.getMessage(),e);
        }
        return new PageBean<DataRepositoryEntity>(dataRepositoryEntities);
    }

    @Override
    public PageBean<JSONObject> getUploadDetail(int id, int currentPage, int pageSize) {
        List uploadDetailList = Lists.newArrayList();
        DataUploadVo dataUploadVo = new DataUploadVo();
        dataUploadVo.setId(id);
        dataUploadVo.setCurrentPage(currentPage);
        dataUploadVo.setPageSize(pageSize);
        try {
            PageHelper.startPage(currentPage, pageSize);
            uploadDetailList = dataUploadDao.getUploadDetail(dataUploadVo);
        } catch (Exception e) {
            logger.error("查询数据包详情列表异常={}",e.getMessage(),e);
        }
        return new PageBean<JSONObject>(uploadDetailList);
    }

    @Override
    public int deleteDataRepository(Integer id) {
        // 删除数据包仓库
        return dataRepositoryDao.deleteDataRepository(id);
    }

    @Override
    public void updateRepository(DataRepositoryEntity entity) {
        // 修改数据包仓库
        try {
            dataRepositoryDao.updateByPrimaryKeySelective(entity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改数据包仓库异常={}",e.getMessage(),e);
        }
    }

    @Override
    public List<ProductTypeEntity> productTypeList(List<Integer> ids) {
        return productTypeDao.productTypeList(ids);
    }

    @Override
    public PddGoodsAuthVO getCurrentCommodityCategory(String name, String shopId) {
        ShopEntity shopEntity = shopDao.queryShopById(shopId);
        if(ObjectUtils.isNull(shopEntity)){
            throw new BusinessException("重新刷新授权!");
        }
        String accessToken = shopEntity.getAccessToken();
        Result<String> result = adapterFeignService.getCurrentCommodityCategory(accessToken);
        String resultValue = result.getValue();
        PddGoodsAuthVO resultVO = new PddGoodsAuthVO();
        List<PddGoodsAuthVO> catsVOS = JSON.parseArray(resultValue, PddGoodsAuthVO.class);
        for (PddGoodsAuthVO vo : catsVOS) {
            List<PddGoodsAuthVO> goodsCatsList = vo.getGoodsCatsList();
            for (PddGoodsAuthVO catsVO : goodsCatsList) {
                List<PddGoodsAuthVO> catsList = catsVO.getGoodsCatsList();
                for (PddGoodsAuthVO pddGoodsAuthVO : catsList) {
                    if(name.equals(pddGoodsAuthVO.getCatName())){
                        resultVO.setCatId(pddGoodsAuthVO.getCatId());
                        resultVO.setCatName(pddGoodsAuthVO.getCatName());
                        resultVO.setLeaf(pddGoodsAuthVO.getLeaf());
                    }
                }
            }
        }
        return resultVO;
    }


    @Override
    public List<ShopVo> queryShopListById(List<String> shopIds) {

        List<ShopEntity> shopEntityList = shopService.queryShopListById(shopIds);

        List<ShopVo> ShopVos = new ArrayList<>();
        for (ShopEntity shopEntity : shopEntityList) {
            // 获取店铺的token
            ShopEntity queryShopById = shopDao.queryShopById(shopEntity.getShopId());
            if(ObjectUtils.isNull(queryShopById)){
                throw new BusinessException("重新刷新授权!");
            }
            String accessToken = queryShopById.getAccessToken();

            //店铺
            ShopVo shopVo = new ShopVo();
            shopVo.setAgtNo(shopEntity.getAgtNo());
            shopVo.setShopId(shopEntity.getShopId());
            shopVo.setShopName(shopEntity.getShopName());

            // 运费模板
            Result<String> listResult = adapterFeignService.getFreightTemplateData(accessToken);
            List<FreightTemplateVO> list = JSON.parseArray(listResult.getValue(), FreightTemplateVO.class);
            shopVo.setFeightTemplate(list);

            // 店铺分类 店铺类型,1:个人 2:企业 3:旗舰店 4:专卖店 5:专营店 6:普通店
            TokenCreateDto tokenCreateDto = new TokenCreateDto();
            tokenCreateDto.setAccessToken(accessToken);
            Result<MallInfoVo> mallInfo = adapterFeignService.getMallInfo(tokenCreateDto);
            Integer shopMerchantType = mallInfo.getValue().getShopMerchantType();
            shopVo.setShopType(shopMerchantType.toString());

            // 关联视频
            Result<String> videoData = adapterFeignService.getVideoData(accessToken);
            List<Object> videoList = JSON.parseArray(videoData.getValue());
            shopVo.setVideoList(videoList);
            ShopVos.add(shopVo);

        }
        return ShopVos;
    }

    @Override
    public List<PddGoodsPropertiesVO> searchPddBrand(String value, Long catId, String shopId) {

        ShopEntity shopEntity = shopDao.queryShopById(shopId);
        if(ObjectUtils.isNull(shopEntity)){
            throw new BusinessException("重新刷新授权!");
        }
        String accessToken = shopEntity.getAccessToken();

        // 获取商品属性
        Result<String> goodsInfo = adapterFeignService.getCurrentGoodsInfo(catId, accessToken);
        String goodsInfoValue = goodsInfo.getValue();
        List<PddGoodsPropertiesVO.GoodsRulePropertiesItem> propertiesVO = JSON.parseArray(goodsInfoValue, PddGoodsPropertiesVO.GoodsRulePropertiesItem.class);
        // 获取ref_pid
        Long refPid = 0L;
        for (PddGoodsPropertiesVO.GoodsRulePropertiesItem propertiesItem : propertiesVO) {
            if(propertiesItem.getName().equals(PddGoodsPropertiesVO.NodeDataEnums.PP.getName())){
                refPid = propertiesItem.getRefPid();
            }
        }
        Result<String> result = adapterFeignService.searchPddBrand(value, catId, refPid, accessToken);
        String resultValue = result.getValue();
        List<PddGoodsPropertiesVO> brands = JSON.parseArray(resultValue, PddGoodsPropertiesVO.class);
        return brands;
    }


    @Override
    public ShopVo synchronousData(String shopId) {
        // 数据同步
        ShopEntity shopEntity = shopDao.queryShopById(shopId);
        if(ObjectUtils.isNull(shopEntity)){
            throw new BusinessException("重新刷新授权!");
        }
        String accessToken = shopEntity.getAccessToken();

        // 根据店铺ID 获取运费模板、分类、品牌
        //店铺
        ShopVo shopVo = new ShopVo();
        shopVo.setAgtNo(shopEntity.getAgtNo());
        shopVo.setShopId(shopEntity.getShopId());

        // 运费模板
        Result<String> listResult = adapterFeignService.getFreightTemplateData(accessToken);
        List<FreightTemplateVO> list = JSON.parseArray(listResult.getValue(), FreightTemplateVO.class);
        shopVo.setFeightTemplate(list);

        // 店铺分类 店铺类型,1:个人 2:企业 3:旗舰店 4:专卖店 5:专营店 6:普通店
        TokenCreateDto tokenCreateDto = new TokenCreateDto();
        tokenCreateDto.setAccessToken(accessToken);
        Result<MallInfoVo> mallInfo = adapterFeignService.getMallInfo(tokenCreateDto);
        Integer shopMerchantType = mallInfo.getValue().getShopMerchantType();
        shopVo.setShopType(shopMerchantType.toString());

        // 关联视频
        Result<String> videoData = adapterFeignService.getVideoData(accessToken);
        List<Object> videoList = JSON.parseArray(videoData.getValue());
        shopVo.setVideoList(videoList);

        return shopVo;
    }

    @Override
    public List<ProductPropertyTemplateEntity> productPropertyTemplateList(String shopId) {
        List<ProductPropertyTemplateEntity> entities = productPropertyTemplateDao.productPropertyTemplateList(shopId);
        return entities;
    }

    @Override
    public ProductPropertyTemplateEntity getProductPropertyTempById(Integer id) {
        ProductPropertyTemplateEntity productPropertyTemplateEntity = productPropertyTemplateDao.selectByPrimaryKey(id);
        return productPropertyTemplateEntity;
    }

    @Override
    public void deleteProductPropertyTempById(Integer id) {
        productPropertyTemplateDao.deleteByPrimaryKey(id);
    }

    @Override
    public void updateOrAddProductPropertyTemp(ProductPropertyTemplateEntity productPropertyTemplate) {
        productPropertyTemplate.setUpdateTime(new Date());
        if(null == productPropertyTemplate.getId()){
            productPropertyTemplateDao.insertSelective(productPropertyTemplate);
        }else {
            productPropertyTemplateDao.updateByPrimaryKeySelective(productPropertyTemplate);
        }
    }

    @Override
    public List<PddGoodsPropertiesVO> getNodeData(String catPropId, String shopId) {
        ShopEntity shopEntity = shopDao.queryShopById(shopId);
        if(ObjectUtils.isNull(shopEntity)){
            throw new BusinessException("重新刷新授权!");
        }
        String accessToken = shopEntity.getAccessToken();

        List<PddGoodsPropertiesVO> resultVO = new ArrayList<>();

        String[] split = catPropId.split("-");
        Long catId = Long.valueOf(split[0]);

        // 查询商品款式、风格、保护套质地、流行元素、商品规格
        // 获取商品属性
        Result<String> goodsInfo = adapterFeignService.getCurrentGoodsInfo(catId, accessToken);
        String goodsInfoValue = goodsInfo.getValue();
        List<PddGoodsPropertiesVO.GoodsRulePropertiesItem> propertiesVO = JSON.parseArray(goodsInfoValue, PddGoodsPropertiesVO.GoodsRulePropertiesItem.class);

        // 款式
        if(split[1].equals(PddGoodsPropertiesVO.NodeDataEnums.KS.getValue())){
            for (PddGoodsPropertiesVO.GoodsRulePropertiesItem propertiesItem : propertiesVO) {
                if(propertiesItem.getName().equals(PddGoodsPropertiesVO.NodeDataEnums.KS.getName())){
                    List<PddGoodsPropertiesVO.PropertiesItemValuesItem> itemValues = propertiesItem.getValues();
                    for (PddGoodsPropertiesVO.PropertiesItemValuesItem itemValue : itemValues) {
                        PddGoodsPropertiesVO rulePropertiesVO = new PddGoodsPropertiesVO();
                        rulePropertiesVO.setVid(itemValue.getVid());
                        rulePropertiesVO.setValue(itemValue.getValue());
                        rulePropertiesVO.setRefPid(propertiesItem.getRefPid());
                        rulePropertiesVO.setValueUnit(propertiesItem.getValueUnit());
                        resultVO.add(rulePropertiesVO);
                    }
                }
            }
            return resultVO;
        }
        // 风格
        if(split[1].equals(PddGoodsPropertiesVO.NodeDataEnums.FG.getValue())){
            for (PddGoodsPropertiesVO.GoodsRulePropertiesItem propertiesItem : propertiesVO) {
                if(propertiesItem.getName().equals(PddGoodsPropertiesVO.NodeDataEnums.FG.getName())){
                    List<PddGoodsPropertiesVO.PropertiesItemValuesItem> itemValues = propertiesItem.getValues();
                    for (PddGoodsPropertiesVO.PropertiesItemValuesItem itemValue : itemValues) {
                        PddGoodsPropertiesVO rulePropertiesVO = new PddGoodsPropertiesVO();
                        rulePropertiesVO.setVid(itemValue.getVid());
                        rulePropertiesVO.setValue(itemValue.getValue());
                        rulePropertiesVO.setRefPid(propertiesItem.getRefPid());
                        rulePropertiesVO.setValueUnit(propertiesItem.getValueUnit());
                        resultVO.add(rulePropertiesVO);
                    }
                }
            }
            return resultVO;
        }
        // 保护套质地
        if(split[1].equals(PddGoodsPropertiesVO.NodeDataEnums.BHTZD.getValue())){
            for (PddGoodsPropertiesVO.GoodsRulePropertiesItem propertiesItem : propertiesVO) {
                if(propertiesItem.getName().equals(PddGoodsPropertiesVO.NodeDataEnums.BHTZD.getName())){
                    List<PddGoodsPropertiesVO.PropertiesItemValuesItem> itemValues = propertiesItem.getValues();
                    for (PddGoodsPropertiesVO.PropertiesItemValuesItem itemValue : itemValues) {
                        PddGoodsPropertiesVO rulePropertiesVO = new PddGoodsPropertiesVO();
                        rulePropertiesVO.setVid(itemValue.getVid());
                        rulePropertiesVO.setValue(itemValue.getValue());
                        rulePropertiesVO.setRefPid(propertiesItem.getRefPid());
                        rulePropertiesVO.setValueUnit(propertiesItem.getValueUnit());
                        resultVO.add(rulePropertiesVO);
                    }
                }
            }
            return resultVO;
        }
        // 流行元素
        if(split[1].equals(PddGoodsPropertiesVO.NodeDataEnums.LXYS.getValue())){
            for (PddGoodsPropertiesVO.GoodsRulePropertiesItem propertiesItem : propertiesVO) {
                if(propertiesItem.getName().equals(PddGoodsPropertiesVO.NodeDataEnums.LXYS.getName())){
                    List<PddGoodsPropertiesVO.PropertiesItemValuesItem> itemValues = propertiesItem.getValues();
                    for (PddGoodsPropertiesVO.PropertiesItemValuesItem itemValue : itemValues) {
                        PddGoodsPropertiesVO rulePropertiesVO = new PddGoodsPropertiesVO();
                        rulePropertiesVO.setVid(itemValue.getVid());
                        rulePropertiesVO.setValue(itemValue.getValue());
                        rulePropertiesVO.setRefPid(propertiesItem.getRefPid());
                        rulePropertiesVO.setValueUnit(propertiesItem.getValueUnit());
                        resultVO.add(rulePropertiesVO);
                    }
                }
            }
            return resultVO;
        }

        // 获取商品规格1
        if(split[1].equals(PddGoodsPropertiesVO.NodeDataEnums.SPECNAME1.getValue())){
            Result<String> goodsSpecifications = adapterFeignService.getGoodsSpecifications(catId, accessToken);
            String goodsSpecificationsValue = goodsSpecifications.getValue();
            List<PddGoodsSpecVO.GoodsSpecListItem> SpecificationsVO = JSON.parseArray(goodsSpecificationsValue, PddGoodsSpecVO.GoodsSpecListItem.class);
            for (PddGoodsSpecVO.GoodsSpecListItem goodsSpecListItem : SpecificationsVO) {
                PddGoodsPropertiesVO rulePropertiesVO = new PddGoodsPropertiesVO();
                rulePropertiesVO.setVid(goodsSpecListItem.getParentSpecId());
                rulePropertiesVO.setValue(goodsSpecListItem.getParentSpecName());
                resultVO.add(rulePropertiesVO);
            }
            return resultVO;
        }
        // 获取商品规格2
        if(split[1].equals(PddGoodsPropertiesVO.NodeDataEnums.SPECNAME2.getValue())){
            Result<String> goodsSpecifications = adapterFeignService.getGoodsSpecifications(catId, accessToken);
            String goodsSpecificationsValue = goodsSpecifications.getValue();
            List<PddGoodsSpecVO.GoodsSpecListItem> SpecificationsVO = JSON.parseArray(goodsSpecificationsValue, PddGoodsSpecVO.GoodsSpecListItem.class);
            for (PddGoodsSpecVO.GoodsSpecListItem goodsSpecListItem : SpecificationsVO) {
                PddGoodsPropertiesVO rulePropertiesVO = new PddGoodsPropertiesVO();
                rulePropertiesVO.setVid(goodsSpecListItem.getParentSpecId());
                rulePropertiesVO.setValue(goodsSpecListItem.getParentSpecName());
                resultVO.add(rulePropertiesVO);
            }
            return resultVO;
        }
        return resultVO;
    }

    @Override
    public List<TitleTemplateEntity> getTitleTemplates() {
        // 获取标题模板
        TitleTemplateEntity entity = new TitleTemplateEntity();
        List<TitleTemplateEntity> templateEntityList = titleTemplateDao.queryAll(entity);
        return templateEntityList;
    }

    @Override
    public TitleTemplateEntity getTitleTemplatesById(Integer id) {
        return titleTemplateDao.selectByPrimaryKey(id);
    }

    @Override
    public void updateOrAddTitleTemplate(TitleTemplateEntity titleTemplate) {
        titleTemplate.setUpdateTime(new Date());
        if(null == titleTemplate.getId()){
            titleTemplateDao.insertSelective(titleTemplate);
        }else {
            titleTemplateDao.updateByPrimaryKeySelective(titleTemplate);
        }
    }

    @Override
    public void deleteTitleTemplateById(Integer id) {
        titleTemplateDao.deleteByPrimaryKey(id);
    }

    // @Override
    // public List<DataUploadImageVO> getSpontaneousTitle(SpontaneousTitleDto spontaneousTitleDto) {
    //     List<DataUploadImageVO> dataUploadImageVOS = new ArrayList<>();
    //     // 获取数据包上传详细数据
    //     Integer repositoryId = spontaneousTitleDto.getRepositoryId();
    //     DataUploadImageEntity uploadImage = new DataUploadImageEntity();
    //     uploadImage.setDetailId(repositoryId);
    //     List<DataUploadImageEntity> uploadImageList = dataUploadImageDao.queryAll(uploadImage);
    //     for (DataUploadImageEntity entity : uploadImageList) {
    //         DataUploadImageVO vo = new DataUploadImageVO();
    //         StringBuffer stringBuffer = this.resultTitle(spontaneousTitleDto, entity);
    //
    //         vo.setId(entity.getId());
    //         vo.setModel(entity.getProductName());
    //         vo.setProductTitle(stringBuffer.toString());
    //         dataUploadImageVOS.add(vo);
    //     }
    //
    //     // 获取自动标题信息
    //     return dataUploadImageVOS;
    // }

    @Override
    public List<DataUploadDetailVO> getDefaultTitle(List<Integer> ids) {
        List<DataUploadDetailVO> resultVO = new ArrayList<>();
        // 获取默认标题
        for (Integer id : ids) {
            DataUploadDetailEntity entity = new DataUploadDetailEntity();
            entity.setDataUploadId(id);
            List<DataUploadDetailEntity> dataUploadDetailEntities = dataUploadDetailDao.queryAll(entity);

            // 查询系列名称
            DataRepositoryEntity dataRepositoryEntity = dataRepositoryDao.selectByPrimaryKey(id);
            for (DataUploadDetailEntity uploadDetail : dataUploadDetailEntities) {
                DataUploadDetailVO vo = new DataUploadDetailVO();
                vo.setId(uploadDetail.getId());
                vo.setReferenceContent(uploadDetail.getProductName());
                vo.setProductTitle((uploadDetail.getProductName() == null ? "" : uploadDetail.getProductName()) +   dataRepositoryEntity.getSeriesName());
                resultVO.add(vo);
            }
        }
        return resultVO;
    }

    @Override
    public TitleTypeVO gainWord(String titleTypeEnum) {
        // 获取词库
        List<TitleWordEntity> titleWordEntities = titleWordDao.TitleWordListByTitleType(titleTypeEnum);

        TitleTypeVO resultVO = new TitleTypeVO();
        // 数据分组
        Map<String, List<TitleWordEntity>> listMap = titleWordEntities.stream().collect(Collectors.groupingBy(TitleWordEntity::getWordType));
        resultVO.setFeatureWords(listMap.get("特性词"));
        resultVO.setGenericWords(listMap.get("通用词"));
        resultVO.setMaterialWords(listMap.get("材质词"));
        resultVO.setStyleWords(listMap.get("风格词"));
        return resultVO;
    }

    @Override
    public void addGainWord(List<TitleWordEntity> titleWordEntity) {
        // 增加词库
        titleWordDao.insertBatch(titleWordEntity);
    }

    @Override
    @Transactional
    public List<Map<String, Object>> releaseGoods(PddProductPropertyDto pddProductPropertyDto) {
        // 商品发布
        List<Map<String, Object>> results = new ArrayList<>();

        ShopEntity shopEntity = shopDao.queryShopById(pddProductPropertyDto.getShopId());
        if(ObjectUtils.isNull(shopEntity)){
            throw new BusinessException("重新刷新授权!");
        }
        String accessToken = shopEntity.getAccessToken();

        // 数据包ID
        Integer repositoryId = pddProductPropertyDto.getCommon().getRepositoryId();
        DataRepositoryEntity dataRepositoryEntity = dataRepositoryDao.selectByPrimaryKey(repositoryId);

        // 生成数据包发布记录
        DataReleaseTaskEntity dataReleaseTask = new DataReleaseTaskEntity();
        dataReleaseTask.setPlatformType("pdd");

        // 获取当前用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        String agtNo = StringUtils.isBlank(user.getUserName()) ? "error" : user.getUserName();
        dataReleaseTask.setAgtNo(agtNo);
        dataReleaseTask.setSeriesName(dataRepositoryEntity.getSeriesName());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(new Date());
        dataReleaseTask.setCreateTime(dateStr);


        // // 校验两件折扣（参数做了校验 因而注释）
        // Result<String> twoPiecesDiscountRule = adapterFeignService.getTwoPiecesDiscountRule(pddProductPropertyDto.getCommon().getCatId(), accessToken);
        // PddGoodsPropertiesVO.CatRuleGetResponseTwoPiecesDiscountRule propertiesVO = JSON.parseObject(twoPiecesDiscountRule.getValue(), PddGoodsPropertiesVO.CatRuleGetResponseTwoPiecesDiscountRule.class);
        // if(propertiesVO.getIfMustTwoPiecesDiscount()){
        //     String pddLJZK = pddProductPropertyDto.getPddLJZK();
        //     Integer minTwoPiecesDiscount = propertiesVO.getMinTwoPiecesDiscount();
        //     Integer maxTwoPiecesDiscount = propertiesVO.getMaxTwoPiecesDiscount();
        //     if (!(Integer.parseInt(pddLJZK) >= Math.min(minTwoPiecesDiscount, maxTwoPiecesDiscount) && Integer.parseInt(pddLJZK)  <= Math.max(minTwoPiecesDiscount, maxTwoPiecesDiscount))) {
        //         throw new BusinessException("拼多多两件折扣填写不在最大折扣和最小折扣之间!");
        //     }
        // }

        DataUploadDetailEntity uploadDetail = new DataUploadDetailEntity();
        uploadDetail.setDataUploadId(repositoryId);
        List<DataUploadDetailEntity> dataUploadDetailEntities = dataUploadDetailDao.queryAll(uploadDetail);
        if(dataUploadDetailEntities.size() == 0){
            throw new BusinessException("数据异常!");
        }

        // 获取发布总数
        dataReleaseTask.setReleaseShopName(pddProductPropertyDto.getCommon().getReleaseShopName());
        dataReleaseTaskDao.insertSelective(dataReleaseTask);

        List<DataReleaseDetailEntity> detailEntities = new ArrayList<>();
        List<AgtWalletDetailEntity> agtWalletDetailEntities = Lists.newArrayList();

        for (DataUploadDetailEntity dataUploadDetailEntity : dataUploadDetailEntities) {

            DataUploadImageEntity uploadImage = new DataUploadImageEntity();
            uploadImage.setDetailId(dataUploadDetailEntity.getId());

            String time = sf.format(new Date());

            // 商品轮播图
            List<String> carouselGallery = new ArrayList<>();
            // 商品详情图
            List<String> detailGallery = new ArrayList<>();
            // 图片类型 1:主图 2: 选项图: 3: 详情图
            List<DataUploadImageEntity> uploadImageList = dataUploadImageDao.queryAll(uploadImage);
            try {
                for (DataUploadImageEntity entity : uploadImageList) {
                    if("1".equals(entity.getImageType())){
                        logger.info("图片地址1：" + entity.getLocalPath());
                        carouselGallery.add(adapterFeignService.goodsImgUpload(entity.getLocalPath(), accessToken).getValue());
                        // 图片上传模式
                        if("1".equals(pddProductPropertyDto.getPddImageUploadType())){
                            adapterFeignService.filesPaceImgUpload(entity.getLocalPath() , accessToken);
                        }
                    }
                    if("3".equals(entity.getImageType())){
                        logger.info("图片地址3：" + entity.getLocalPath());
                        detailGallery.add(adapterFeignService.goodsImgUpload(entity.getLocalPath(), accessToken).getValue());
                    }
                }
            }catch (Exception e){
                throw new BusinessException("图片上传异常!");
            }
            pddProductPropertyDto.setDataUploadImageVO(uploadImageList.stream().filter(e -> e.getImageType().equals("2")).collect(Collectors.toList()));
            pddProductPropertyDto.getCommon().setCarouselGallery(carouselGallery);
            pddProductPropertyDto.getCommon().setDetailGallery(detailGallery);

            // 数据包发布记录详情设置参数
            DataReleaseDetailEntity detail = new DataReleaseDetailEntity();
            detail.setReleaseId(dataReleaseTask.getId());
            detail.setSeriesName(dataRepositoryEntity.getSeriesName());

            // 设置标题
            List<DataUploadDetailVO> dataUploadDetailVO = pddProductPropertyDto.getDataUploadDetailVO();
            for (DataUploadDetailVO uploadDetailVO : dataUploadDetailVO) {
                if(uploadDetailVO.getId() == dataUploadDetailEntity.getId()){
                    pddProductPropertyDto.getCommon().setGoodsName(uploadDetailVO.getProductTitle());
                    // 数据包发布记录详情设置商品标题
                    detail.setGoodsTitle(uploadDetailVO.getProductTitle());
                }
            }

            // 主图随机排放
            if(pddProductPropertyDto.getCommon().isMasterPicRandom()){
                Collections.shuffle(carouselGallery);
            }

            // 商品间隔发布（单位/秒）
            if(!StringUtils.isBlank(pddProductPropertyDto.getCommon().getIntervalSec())){
                try {
                    BigDecimal sub = new BigDecimal(pddProductPropertyDto.getCommon().getIntervalSec()).multiply(new BigDecimal(1000));
                    Thread.sleep(Long.parseLong(sub.toString()));
                } catch(Exception e){
                    throw new BusinessException("商品间隔发布单位错误!");
                }
            }
            // 发布商品
            Result<Map<String, Object>> result = adapterFeignService.releaseGoods(pddProductPropertyDto, accessToken);


            // 分解返回结果 入库数据包发布记录
            Iterator<Map.Entry<String, Object>> entries = result.getValue().entrySet().iterator();
            while(entries.hasNext()) {
                Map.Entry<String, Object> entry = entries.next();
                // 入库数据包发布记录详情 成功和失败
                if("false".equals(entry.getKey())){
                    Object entryValue = entry.getValue();
                    detail.setReleaseStatus("2");
                    detail.setMessage(entryValue +"");
                    detail.setOutGoodsId(0L);
                }
                if("true".equals(entry.getKey())){
                    Object entryValue = entry.getValue();
                    detail.setReleaseStatus("1");
                    PddGoodsPropertiesVO.GoodsAddResponse goodsAdd = JSON.parseObject(entryValue.toString(), PddGoodsPropertiesVO.GoodsAddResponse.class);
                    detail.setOutGoodsId(goodsAdd.getGoodsId());
                }
            }
            // 数据包发布记录详情入集合
            detailEntities.add(detail);
            if (!StringUtils.isNull(result.getValue().get("true"))){
                // 商品发布成功扣, 扣除用户的积分余额
                Map<String, Object> map = new HashMap<>();
                map.put("chargeMoney", -2);
                map.put("agtPhone", agtNo);
                map.put("shopId",pddProductPropertyDto.getShopId());
                map.put("shopName",shopEntity.getShopName());
                map.put("remark","发布商品:"+dataUploadDetailEntity.getId());
                try {
                    agentWalletDao.updateAgtWallet(map);
                    if (CollectionUtils.isNotEmpty(map) && null != map.get("result")) {
                        if (Integer.parseInt(map.get("result").toString()) == CommonConstants.PROCEDURE_SUCCESS) {
                            logger.info("更新用户可用积分成功");
                        } else if (Integer.parseInt(map.get("result").toString()) == CommonConstants.PROCEDURE_FAIL) {
                            throw new ServiceException(CommonConstants.NOT_ENOUGH_BALANCE, "用户可用积分不足!");
                        } else if (Integer.parseInt(map.get("result").toString()) == CommonConstants.PROCEDURE_SYSTEM_ERROR){
                            throw new BusinessException("系统错误,存储过程执行异常!");
                        } else if (Integer.parseInt(map.get("result").toString()) == CommonConstants.PROCEDURE_PARAM_ERROR){
                            throw new BusinessException("参数错误, 商户账号或金额不能为空!");
                        } else if (Integer.parseInt(map.get("result").toString()) == CommonConstants.PROCEDURE_WALLET_NOT_EXIST){
                            throw new BusinessException("用户钱包不存在!");
                        }
                    } else {
                        throw new BusinessException("提现申请冻结余额失败!");
                    }
                } catch (Exception e) {
                    logger.error("执行更新用户积分sql异常,e={}", e.getMessage());
                    throw new BusinessException("执行更新用户积分sql异常!");
                }
            }
            results.add(result.getValue());
        }

        // 数据包发布记录详情批量入库
        dataReleaseDetailDao.batchInsert(detailEntities);
        // 入库任务成功和失败数量
        long succeed = results.stream().filter(e -> !(StringUtils.isNull(e.get("true")))).count();
        long fail = results.stream().filter(e -> !(StringUtils.isNull(e.get("false")))).count();
        DataReleaseTaskEntity taskEntity = new DataReleaseTaskEntity();
        taskEntity.setId(dataReleaseTask.getId());
        taskEntity.setSuccessCount((int) succeed);
        taskEntity.setFailCount((int) fail);
        taskEntity.setTotalCount(dataUploadDetailEntities.size());
        dataReleaseTaskDao.updateByPrimaryKeySelective(taskEntity);
        // 商品发布成功后,
        return results;
    }

    @Override
    public List<List<Map<String, Object>>> batchReleaseGoods(List<PddProductPropertyDto> pddProductPropertyDto) {
        // 批量发布商品
        List<List<Map<String, Object>>> results = new ArrayList<>();
        for (PddProductPropertyDto productPropertyDto : pddProductPropertyDto) {
            List<Map<String, Object>> releaseGoods = this.releaseGoods(productPropertyDto);
            results.add(releaseGoods);
        }
        return results;
    }

    @Override
    public void exportWillReleaseExcel(HttpServletResponse response, String seriesName, Integer repositoryId) {
        List<DataUploadImageEntity> uploadImageList = dataUploadImageDao.queryAllByDataUploadId(repositoryId);
        try {
            ExeclUtil.exportExcel(response, uploadImageList, seriesName + "_数量" + uploadImageList.size());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void importWillReleaseExcel(PddProductPropertyDto pddProductPropertyDto, MultipartFile file) {
        try {
            List<DataUploadImageEntity> importData = ExeclUtil.importExcel(file);
            this.releaseGoods(pddProductPropertyDto);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void prolongExpireTime(Integer id) {
        // 延长15天时间
        DataRepositoryEntity dataRepositoryEntity = dataRepositoryDao.selectByPrimaryKey(id);

        // 分钟
        int expiresTime = dataRepositoryEntity.getExpiresTime();
        dataRepositoryEntity.setExpiresTime(expiresTime + 21600);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(new Date());
        dataRepositoryEntity.setCreateTime(dateStr);
        dataRepositoryDao.updateByPrimaryKeySelective(dataRepositoryEntity);
    }

    @Override
    @Transactional
    public void copySeries(Integer id, Integer count) {
        // 生成副本

        // 查询原有数据
        DataRepositoryEntity dataRepositoryEntity = dataRepositoryDao.selectByPrimaryKey(id);

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(new Date());

        String seriesName = dataRepositoryEntity.getSeriesName();
        for (int i = 0; i < count; i++) {
            StringBuilder random = RandomUtil.getRandom(6);
            dataRepositoryEntity.setSeriesName(seriesName + "_副本_" + random + "_" + (i+1));
            dataRepositoryEntity.setCreateTime(dateStr);
            dataRepositoryDao.insertSelective(dataRepositoryEntity);
            int repositoryEntityId = dataRepositoryEntity.getId();

            // 查询原来ID的数据
            DataUploadDetailEntity detail = new DataUploadDetailEntity();
            detail.setDataUploadId(id);
            List<DataUploadDetailEntity> dataUploadDetailEntities = dataUploadDetailDao.queryAll(detail);

            for (DataUploadDetailEntity detailEntity : dataUploadDetailEntities) {
                int detailEntityId = detailEntity.getId();
                detailEntity.setDataUploadId(repositoryEntityId);
                detailEntity.setCreateTime(dateStr);

                // 入库上传详细
                DataUploadImageEntity uploadImage = new DataUploadImageEntity();
                uploadImage.setDetailId(detailEntityId);
                List<DataUploadImageEntity> uploadImageEntities = dataUploadImageDao.queryAll(uploadImage);
                dataUploadDetailDao.insertSelective(detailEntity);

                // 入库上传详细图片
                for (DataUploadImageEntity uploadImageEntity : uploadImageEntities) {
                    uploadImageEntity.setDetailId(detailEntity.getId());
                    uploadImageEntity.setCreateTime(dateStr);
                    dataUploadImageDao.insertSelective(uploadImageEntity);
                }
            }
        }
    }

    @Override
    public PageBean<DataUploadDetailVO> queryProductRecordList(DataUploadDetailVO dataUploadDetailVO) {
        // 查询产品数据列表
        List<DataUploadDetailVO> uploadDetailList = Lists.newArrayList();
        try {
            PageHelper.startPage(dataUploadDetailVO.getCurrentPage(), dataUploadDetailVO.getPageSize());
            uploadDetailList = dataRepositoryDao.queryProductRecordList(dataUploadDetailVO);
        } catch (Exception e) {
            logger.error("查询数据包详情列表异常={}",e.getMessage(),e);
        }
        return new PageBean<>(uploadDetailList);
    }

    @Override
    @Transactional
    public void updateProductRecord(DataUploadDetailVO dataUploadDetailVO) {
        // 修改产品数据
        DataUploadDetailEntity entity = new DataUploadDetailEntity();
        entity.setId(dataUploadDetailVO.getId());
        entity.setProductName(dataUploadDetailVO.getProductName());
        try {
            dataUploadDetailDao.updateProductRecord(entity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改产品数据异常={}",e.getMessage(),e);
        }
    }

    @Override
    @Transactional
    public void deleteProductRecordById(Integer id) {
        // 删除产品数据
        try {
            dataUploadDetailDao.deleteProductRecordById(id);
            dataUploadImageDao.deleteDataUploadImageByDetailId(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除产品数据异常={}",e.getMessage(),e);
        }
    }

    @Override
    public ProductGoodsDataVO getProductGoodsData(Integer id) {

        // 预发布查看
        ProductGoodsDataVO dataVO = new ProductGoodsDataVO();

        // 查询系列数据
        DataUploadDetailEntity uploadDetail = dataUploadDetailDao.selectByPrimaryKey(id);
        dataVO.setProductData(uploadDetail);

        DataUploadImageEntity entity = new DataUploadImageEntity();
        entity.setDetailId(id);
        List<DataUploadImageEntity> dataUploadImageEntities = dataUploadImageDao.queryAll(entity);
        // 图片类型 1:主图 2: 选项图: 3: 详情图
        // 查询主图
        List<DataUploadImageEntity> mainPictures = dataUploadImageEntities.stream().filter(e -> "1".equals(e.getImageType())).collect(Collectors.toList());
        dataVO.setMainPictures(mainPictures);

        // 查询详情图
        List<DataUploadImageEntity> details = dataUploadImageEntities.stream().filter(e -> "3".equals(e.getImageType())).collect(Collectors.toList());
        dataVO.setDetails(details);

        // 查询规格
        List<DataUploadImageEntity> options = dataUploadImageEntities.stream().filter(e -> "2".equals(e.getImageType())).collect(Collectors.toList());
        dataVO.setOptions(options);

        return dataVO;
    }

    @Override
    public void insertRepositoryData(DataRepositoryEntity dataRepositoryEntity) {
        dataRepositoryDao.insertDataRepository(dataRepositoryEntity);
    }

    @Override
    public void updateRepositoryData(DataRepositoryEntity dataRepositoryEntity) {
        dataRepositoryDao.updateDataRepository(dataRepositoryEntity);
    }


    private StringBuffer resultTitle(SpontaneousTitleDto spontaneousTitleDto, DataUploadImageEntity entity){

        StringBuffer resultTitle = new StringBuffer();

        // 品牌
        List<String> brands = new ArrayList<>();
        brands.add("OPPO");
        resultTitle.append("OPPO");

        // 型号
        List<String> models = new ArrayList<>();
        models.add("A5");
        models.add("A6");

        // resultTitle.append(entity.getProductName());

        // 标题生成方式 1-标题词优先 2-型号错词优先
        Integer makeType = spontaneousTitleDto.getMakeType();
        if(1 == makeType){
            // 标题词设置
            WordLibraryDto wordLibrary = spontaneousTitleDto.getWordLibrary();
            List<String> customWords = wordLibrary.getCustomWords();
            for (String customWord : customWords) {
                String[] split = customWord.split("/");
                for (int i = 0; i < split.length; i++) {
                    resultTitle.append(split[i]);
                }
            }
            List<String> materialWords = wordLibrary.getMaterialWords();
            for (String materialWord : materialWords) {
                resultTitle.append(materialWord);
            }
            List<String> styleWords = wordLibrary.getStyleWords();
            for (String styleWord : styleWords) {
                resultTitle.append(styleWord);
            }
            List<String> featureWords = wordLibrary.getFeatureWords();
            for (String featureWord : featureWords) {
                resultTitle.append(featureWord);
            }
            List<String> genericWords = wordLibrary.getGenericWords();
            for (String genericWord : genericWords) {
                resultTitle.append(genericWord);
            }
        }
        if(2 == makeType){

        }
        // 多型号标题制作（开启该功能,系统将会读取匹配数据中的所有型号用来制作标题，该功能还属于测试阶段,开启后请仔细检查预览中的数据再进行提交!）
        boolean moreModelMake = spontaneousTitleDto.isMoreModelMake();
        if(moreModelMake){
            for (String model : models) {
                resultTitle.append(model);
            }
        }

        // 多型号排序规则1-根据产品型号顺序 2-首型号固定，其他型号随机 3-随机排放
        Integer morePhoneOrderType = spontaneousTitleDto.getMorePhoneOrderType();
        if(1 == morePhoneOrderType){
            for (String model : models) {
                int indexOf = resultTitle.indexOf(model);
                if(indexOf == -1){
                    resultTitle.append(model);
                }
            }
        }

        if(2 == morePhoneOrderType){
            if(models.size() > 2){
                // 过滤掉首型号
                List<String> morePhoneOrderTypeModels = models.stream()
                        .map(String::valueOf)
                        .filter(n -> n.equals(models.get(0))
                        ).collect(Collectors.toList());

                // 随机
                Collections.shuffle(morePhoneOrderTypeModels);
                // 替换原有型号为空
                for (String model : morePhoneOrderTypeModels) {
                    resultTitle.replace(resultTitle.indexOf(model), resultTitle.indexOf(model) +1 ,"");
                }

                // 重新添加随机品牌
                for (String typeModel : morePhoneOrderTypeModels) {
                    resultTitle.append(typeModel);
                }
            }else {
                for (String model : models) {
                    int indexOf = resultTitle.indexOf(model);
                    if(indexOf == -1){
                        resultTitle.append(model);
                    }
                }
            }
        }
        if(3 == morePhoneOrderType){
            List<String> morePhoneOrderTypeModels = models.stream().map(String::valueOf).collect(Collectors.toList());
            // 然后使用Collections类的shuffle方法随机排列List
            Collections.shuffle(morePhoneOrderTypeModels);

            // 替换原有型号为空
            for (String model : models) {
                resultTitle.replace(resultTitle.indexOf(model), resultTitle.indexOf(model) +1 ,"");
            }

            // 重新添加随机品牌
            for (String typeModel : morePhoneOrderTypeModels) {
                resultTitle.append(typeModel);
            }
        }

        // 标题前缀
        String suffix = spontaneousTitleDto.getSuffix();
        if(!StringUtils.isEmpty(suffix)){
            resultTitle.insert(0, suffix);
        }

        // 标题后缀
        String prefix = spontaneousTitleDto.getPrefix();
        if(!StringUtils.isEmpty(prefix)){
            resultTitle.append(prefix);
        }

        // 品牌名称大写
        boolean brandCapital = spontaneousTitleDto.isBrandCapital();
        if(brandCapital){
            for (String brand : brands) {
                if(-1 < resultTitle.indexOf(brand)){
                    resultTitle.replace(resultTitle.indexOf(brand), resultTitle.indexOf(brand) + brand.length() , brand.toUpperCase());
                }
            }
        }

        // 型号名称全部大写
        boolean modelNameAllCapital = spontaneousTitleDto.isModelNameAllCapital();
        if(modelNameAllCapital){
            for (String model : models) {
                if(-1 < resultTitle.indexOf(model)){
                    resultTitle.replace(resultTitle.indexOf(model), resultTitle.indexOf(model) + model.length() , model.toUpperCase());
                }
            }
        }

        // 品牌和型号之间加入空格
        boolean brandToModelJoinBlank = spontaneousTitleDto.isBrandToModelJoinBlank();
        if(brandToModelJoinBlank){
            for (String brand : brands) {
                resultTitle.replace(resultTitle.indexOf(brand), resultTitle.indexOf(brand) + brand.length() , brand + " ");
            }
        }

        // 型号格式化（开启此功能后讲会对型号进行格式化,主要体现在型号首字母大写,5G/4G等型号标识会加入空格等）
        boolean modelFormatting = spontaneousTitleDto.isModelFormatting();
        if(modelFormatting){
            for (String model : models) {
                char firstChar = model.charAt(0);
                char upperFirstChar = Character.toUpperCase(firstChar);
                String result = upperFirstChar + model.substring(1);
                resultTitle.replace(resultTitle.indexOf(model), resultTitle.indexOf(model) + model.length()  , result);
            }
            int indexOf4 = resultTitle.indexOf("4G");
            if(indexOf4 > 0){
                resultTitle.replace(indexOf4, indexOf4 + 1 , "4G ");
            }
            int indexOf5 = resultTitle.indexOf("5G");
            if(indexOf5 > 0){
                resultTitle.replace(indexOf5, indexOf5 + 1 , "5G ");
            }
        }

        // 加入产品名称 -1-不加入 1-加入至标题前 2-加入至标题后 3-随机加入
        Integer addProductNameType = spontaneousTitleDto.getAddProductNameType();
        if(1 == addProductNameType){



        }
        if(2 == addProductNameType){

        }
        if(3 == addProductNameType){

        }

        // 首个型号随机规则 -1-不随机 1-按型号随机 2-按型号+错词随机 3-按我的词库定义的型号随机
        Integer firstModelShuffleType = spontaneousTitleDto.getFirstModelShuffleType();
        if(1 == firstModelShuffleType){

        }
        if(2 == firstModelShuffleType){

        }
        if(3 == firstModelShuffleType){

        }

        // 免型号匹配（免型号匹配将会忽略系统词库型号的匹配,匹配数据将直接变更为对应型号,被生成的标题中将不在包含型号错词,将全部由自定义词语/类型词进行随机组合! 开启该功能后诸多功能将会失效!）
        boolean noMatching = spontaneousTitleDto.isNoMatching();
        if(noMatching){

        }

        // 标题优先添加入网型号（开启该功能,系统会优先读取您自定义的对应设备型号,若没有则会读取系统录入的设备型号。该词将会优先出现在标题之中。）
        boolean deviceName = spontaneousTitleDto.isDeviceName();
        if(deviceName){

        }

        // 加入父品牌（荣耀、真我、iqoo等子品牌型号数据将会在标题型号的前缀中加入父品牌华为、oppo、vivo等）
        boolean addParentBrand = spontaneousTitleDto.isAddParentBrand();
        if(addParentBrand){

        }

        // 去除重复品牌词
        boolean wipeRepetitionBrandWord = spontaneousTitleDto.isWipeRepetitionBrandWord();
        if(wipeRepetitionBrandWord){

        }

        // 系统自动补词（如果开启此功能,在标题低于平台对应的字符数时,将使用系统词库进行自动补充!）
        boolean autoFillWord = spontaneousTitleDto.isAutoFillWord();
        if(autoFillWord){

        }

        // 型号后缀（型号后缀为数据匹配成功后,正常型号后面出现的第一个词语,如果不填默认则为手机壳或钢化膜）
        String modelSuffix = spontaneousTitleDto.getModelSuffix();
        if(!StringUtils.isEmpty(modelSuffix)){

        }

        // 多型号分割符（若标题存在多个型号,系统将会对多个型号进行分割组合,例如:iphone11/13/13ProMax/14Pro 等进行这样的组词）
        String morePhoneSplitSymbol = spontaneousTitleDto.getMorePhoneSplitSymbol();
        if(!StringUtils.isEmpty(morePhoneSplitSymbol)){

        }

        // 顺序随机（自定义词会优先于下方选择的词出现在标题之中,默认为随机顺序,若想按照顺序拼接请关闭旁边的 顺序随机 的开关）
        boolean customWordsRandom = spontaneousTitleDto.isCustomWordsRandom();
        if(customWordsRandom){

        }

        // 品牌所有型号加'适用':
        String brandPreventIllegal = spontaneousTitleDto.getBrandPreventIllegal();
        if(!StringUtils.isEmpty(brandPreventIllegal)){

        }

        // 型号加入中文品牌（开启此功能后,如果型号存在中文品牌则会加入到标题中,例如iPhone的中文品牌为苹果,realme为真我）
        boolean joinChineseBrand = spontaneousTitleDto.isJoinChineseBrand();
        if(joinChineseBrand){

        }

        // 全自动构成标题（如果开启此功能,则选择或自己定义的词语都将会失效,将由系统全自动进行解析匹配,建议不使用此功能!!!）
        boolean autoTitleAnalysis = spontaneousTitleDto.isAutoTitleAnalysis();
        if(autoTitleAnalysis){

        }

        // 词语类型
        String titleTypeEnum = spontaneousTitleDto.getTitleTypeEnum();
        if(!StringUtils.isEmpty(titleTypeEnum)){

        }

        return resultTitle;
    }

    private String generateTransactionNo() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 20);
    }
}
